#!/bin/env/python3
import json
import random
from redis import Redis
from aliyunsdkcore.client import AcsClient
from aliyunsdkcore.request import CommonRequest

from info import redis_store, constants

ACCESS_KEY_ID = "LTAI4GCCB5nL7usYvdzCqMHU"
ACCESS_KEY_SECRTE = "SGlMuQr7NOXYgd3DVaEON4F6uQnQlA"


# decode_r.. 表示是否对响应的数据进行解码


class SMS:
    def __new__(cls, *args, **kwargs):
        if not hasattr(SMS, "_instance"):
            cls._instance = super().__new__(cls, *args, **kwargs)
            cls._instance.client = client = AcsClient(ACCESS_KEY_ID, ACCESS_KEY_SECRTE, 'cn-杭州')
        return cls._instance

    # def __init__(self):
    #     self.client

    def send(self, phone):
        # code = '123456 '
        # 存放进缓存
        code =random.randint(100000, 999999)
        request = CommonRequest()
        request.set_accept_format('json')
        request.set_domain('dysmsapi.aliyuncs.com')
        request.set_method('POST')
        request.set_protocol_type('https')  # https | http
        request.set_version('2017-05-25')
        request.set_action_name('SendSms')

        request.add_query_param('RegionId', "cn-hangzhou")
        print(phone)
        request.add_query_param('PhoneNumbers', phone)
        request.add_query_param('SignName', "题酷")
        request.add_query_param('TemplateCode', "SMS_202551552")
        request.add_query_param('TemplateParam', '{"code": %s}' % code)

        response = self.client.do_action_with_exception(request)
        # python2:  print(response)
        if json.loads(str(response, encoding='utf-8')).get("Message") == "OK":
            redis_store.set(phone, code, constants.SMS_CODE_REDIS_EXPIRES)
            return 0
        return -1

def sendcode(phone):
    sms = SMS()
    return sms.send(phone)

# if __name__ == '__main__':
#     print(id(SMS()))
#     print(id(SMS()))
#     print(id(SMS()))
